package base.web.tools.result;

import base.web.actions.BaseAction;
import com.opensymphony.xwork2.ActionInvocation;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-6-15
 * Time: 下午3:48
 * To change this template use File | Settings | File Templates.
 */
public class JsonResult extends BaseResult{
    @Override
    protected void doExecute(String s, ActionInvocation actionInvocation) throws Exception {
        ServletContext sc = ServletActionContext.getServletContext();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding(request.getCharacterEncoding());
		response.setContentType("application/json");

		PrintWriter output = response.getWriter();
		BaseAction baseAction = (BaseAction) actionInvocation.getAction();

		output.flush();

		JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));

		JSONObject js=JSONObject.fromObject(baseAction.getModel(),jsonConfig);
		js.put("code",new Integer(baseAction.getCode()));
		js.put("msg", baseAction.getMsg());
        js.put("expMsg", baseAction.getExpMsg());
        js.put("code", baseAction.getCode());
		//js.put("expMsg", baseAction.getExpMsg());
		js.write(output);
        js.clear();
    }
}
